using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using CMS.api.Entity;
using CMS.api.Model;
using CMS.api.Repository;
using CMS.api.Utils;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using Microsoft.AspNetCore.Hosting;

namespace CMS.api.Controllers
{

    [ApiController]
    [Route("[controller]")]
    public class FileController : ControllerBase
    {
        /// <summary>
        /// 用户数据库增删改查的属性
        /// </summary>
        // 用户表
        private ICURDable<Users> _UsersRepository;
        // 文章表
        private ICURDable<Articles> _ArticlesRepository;
        // 文章分类表
        private ICURDable<Article_Category> _Article_CategoryRepository;
        // 文章评论表
        private ICURDable<Article_Comment> _Article_CommentRepository;
        // 文章内容表
        private ICURDable<Article_Content> _Article_ContentRepository;
        // 文章图片表
        private ICURDable<Article_Picture> _Article_PictureRepository;
        // 文章点赞表
        private ICURDable<Article_Like> _Article_LikeRepository;
        // 文章点反对表
        private ICURDable<Article_Low> _Article_LowRepository;
        // 文章浏览记录表
        private ICURDable<Article_View> _Article_ViewRepository;
        // 用于保存token的配置信息
        private TokenParameter _tokenParameter;
        // 用于读取配置文件的信息
        private readonly IConfiguration _configuration;
        private ICURDable<Slideshow> _SlideshowRepository;

        public FileController(
            IConfiguration configuration,
            ICURDable<Articles> ArticlesRepository,
            ICURDable<Article_Category> Article_CategoryRepository,
            ICURDable<Article_Comment> Article_CommentRepository,
            ICURDable<Article_Content> Article_ContentRepository,
            ICURDable<Article_Picture> Article_PictureRepository,
            ICURDable<Article_Like> Article_LikeRepository,
            ICURDable<Article_Low> Article_LowRepository,
            ICURDable<Article_View> Article_ViewRepository,
            ICURDable<Users> UsersRepository,
            ICURDable<Slideshow> Slideshow
        )
        {
            _ArticlesRepository = ArticlesRepository;
            _Article_CategoryRepository = Article_CategoryRepository;
            _Article_CommentRepository = Article_CommentRepository;
            _Article_ContentRepository = Article_ContentRepository;
            _Article_PictureRepository = Article_PictureRepository;
            _Article_LikeRepository = Article_LikeRepository;
            _Article_LowRepository = Article_LowRepository;
            _Article_ViewRepository = Article_ViewRepository;
            _UsersRepository = UsersRepository;
            _SlideshowRepository = Slideshow;


            _configuration = configuration;
            _tokenParameter =
                _configuration
                    .GetSection("TokenParameter")
                    .Get<TokenParameter>();
        }


        /// <summary>
        /// 上传文件(包括图片)
        /// </summary>
        /// <param name="model">需要传入:文件或图片</param>
        /// <returns></returns>
        [HttpPost, Route("UploadImage")]
        public dynamic UploadFile(IFormCollection model)
        {
            // 获得当前应用所在的完整路径（绝对地址）
            var filePath = Directory.GetCurrentDirectory();

            // 通过配置文件获得存放文件的相对路径
            string path = _configuration["UploadFilesPath"];

            // 最终存放文件的完整路径
            var preFullPath = Path.Combine(filePath, path);
            // 如果路径不存在，则创建
            if (!Directory.Exists(preFullPath))
            {
                Directory.CreateDirectory(preFullPath);
            }



            var resultPath = new List<string>();
            // var uploadfiles = new List<UploadFileInfo>();
            foreach (IFormFile file in model.Files)
            {
                if (file.Length > 0)
                {
                    var fileName = file.FileName;
                    var extName = fileName.Substring(fileName.LastIndexOf("."));//extName包含了“.”
                    var rndName = Guid.NewGuid().ToString("N") + extName;
                    var tempPath = Path.Combine(path, rndName).Replace("\\", "/");
                    using (var stream = new FileStream(Path.Combine(filePath, tempPath), FileMode.CreateNew))//Path.Combine(_env.WebRootPath, fileName)
                    {
                        file.CopyTo(stream);
                    }
                    // 此处地址可能带有两个反斜杠，虽然也能用，比较奇怪，统一转换成斜杠，这样在任何平台都有一样的表现
                    resultPath.Add(tempPath.Replace("\\", "/"));
                }
            }



            var res = new
            {
                Code = 200,
                Data = new
                {
                    resultPath = resultPath[0],
                },
                Msg = "上传成功"
            };
            return JsonHelper.Serialize(res);


        }





        /// <summary>
        /// 上传文件(包括图片)
        /// </summary>
        /// <param name="model">需要传入:文件或图片</param>
        /// <returns></returns>
        [HttpPost, Route("UploadImageById/{id}")]
        public dynamic UploadImageById(int id, IFormCollection model)
        {
            // 获得当前应用所在的完整路径（绝对地址）
            var filePath = Directory.GetCurrentDirectory();

            // 通过配置文件获得存放文件的相对路径
            string path = _configuration["UploadFilesPath"];

            // 最终存放文件的完整路径
            var preFullPath = Path.Combine(filePath, path);
            // 如果路径不存在，则创建
            if (!Directory.Exists(preFullPath))
            {
                Directory.CreateDirectory(preFullPath);
            }

            var resultPath = new List<string>();
            // var uploadfiles = new List<UploadFileInfo>();
            foreach (IFormFile file in model.Files)
            {
                if (file.Length > 0)
                {
                    var fileName = file.FileName;
                    var extName = fileName.Substring(fileName.LastIndexOf("."));//extName包含了“.”
                    var rndName = Guid.NewGuid().ToString("N") + extName;
                    var tempPath = Path.Combine(path, rndName).Replace("\\", "/");
                    using (var stream = new FileStream(Path.Combine(filePath, tempPath), FileMode.CreateNew))//Path.Combine(_env.WebRootPath, fileName)
                    {
                        file.CopyTo(stream);
                    }
                    // 此处地址可能带有两个反斜杠，虽然也能用，比较奇怪，统一转换成斜杠，这样在任何平台都有一样的表现
                    resultPath.Add(tempPath.Replace("\\", "/"));
                }
            }


            var s = _SlideshowRepository.Table.Where(x => x.Id == id).FirstOrDefault();
            if (s == null)
            {
                var sh = new Slideshow
                {
                    SlideshowUrl = resultPath[0],
                };

                _SlideshowRepository.Inster(sh);
                var tmp = new
                {
                    Code = 200,
                    Data = sh,
                    Msg = "添加图片成功"
                };

                return JsonHelper.Serialize(tmp);

            }
            else
            {
                s.SlideshowUrl = resultPath[0];
                s.UpdatedTime = DateTime.Now;
                var tmp = new
                {
                    Code = 200,
                    Data = s,
                    Msg = "添加图片成功"
                };

                return JsonHelper.Serialize(tmp);
            }

        }


        

        // [Route("{prePath/{id}}")]
        // [HttpGet]
        // public FileContentResult Get(int id)
        // {
        //     // 获取本机的地址
        //     var currentPath = Directory.GetCurrentDirectory();
        //     var ap = _Article_PictureRepository.GetById(id);

        //     if(ap == null){
        //         return new FileContentResult(new byte[0],"image/jpeg");
        //     }

        //     var fullPath = Path.Combine(currentPath,ap.ArticlePictureUrl);
            
        //     using (var sw = new FileStream(fullPath, FileMode.Open))
        //     {
        //         var contenttype = 
        //         var bytes = new byte[sw.Length];
        //         sw.Read(bytes, 0, bytes.Length);
        //         sw.Close();
        //         return new FileContentResult(bytes, fileType);
        //     }
        // }


    }

}